package com.parttimetask.activities.main;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.parttimetask.adapter.HomeListAdapter;
import com.parttimetask.bean.HomeListBean;
import com.parttimetask.databinding.FragmentHomeBinding;
import com.parttimetask.utils.Http;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class HomeFragment extends Fragment {
    private FragmentHomeBinding binding;
    private HomeListAdapter adp;
    private final List<HomeListBean> data=new ArrayList<>();

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        adp=new HomeListAdapter(requireActivity(),data);
        binding.homeList.setAdapter(adp);
        refresh();
        return binding.getRoot();
    }
    private void refresh() {
        Http.get("configure/getConfigure/", new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) { e.printStackTrace(); }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                requireActivity().runOnUiThread(() -> {
                    try {
                        JSONObject bo = new JSONObject(response.body().string());
                        data.add(new HomeListBean(Http.BASE_URL+"files/jobIcon/PBpower.png", "Top Recommend-PBpower", bo.getJSONObject("pb").getString("look"), bo.getJSONObject("pb").getString("salary"), bo.getJSONObject("pb").getString("payType"), bo.getJSONObject("pb").getString("joyType"), bo.getJSONObject("pb").getString("applyLink")));
                        data.add(new HomeListBean(Http.BASE_URL+"files/jobIcon/Solar.png", "Top Recommend-Solar Factory", bo.getJSONObject("solar").getString("look"), bo.getJSONObject("solar").getString("salary"), bo.getJSONObject("solar").getString("payType"), bo.getJSONObject("solar").getString("joyType"), bo.getJSONObject("solar").getString("applyLink")));
                        adp.notifyDataSetChanged();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}